<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="应用名称" prop="appName">
              <el-input v-model="queryParams.appName" placeholder="请输入应用名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['know:wikiApps:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['know:wikiApps:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['know:wikiApps:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['know:wikiApps:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="应用名称" align="center" prop="appName" />
        <el-table-column label="应用秘钥" align="center" prop="appKey" />
        <el-table-column label="应用类型" align="center" prop="wikiType">
          <template #default="scope">
            {{ getDictDataLabel(scope.row.wikiType) }}
          </template>
        </el-table-column>
        <el-table-column label="知识库名称" align="center">
          <template #default="scope">
            <div v-if="scope.row.wikiNames">
              <el-tag v-for="(item, index) in scope.row.wikiNames.split(',')" :key="index" class="tag_class">
                {{ item }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="应用描述" align="center" prop="description" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['know:wikiApps:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['know:wikiApps:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="权限" placement="top">
              <el-button link type="primary" icon="UserFilled" @click="openRoleDialog(scope.row)"
                v-hasPermi="['know:wikiApps:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改知识库配置11对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dialogFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用秘钥" prop="appKey">
          <el-input v-model="form.appKey" placeholder="请输入应用秘钥" />
        </el-form-item>
        <el-form-item label="应用类型" prop="wikiType">
          <el-select v-model="form.wikiType" placeholder="请选择应用类型" style="width: 338px">
            <el-option v-for="item in wiki_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="应用描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入应用描述" />
        </el-form-item>
        <el-form-item label="关联知识库" prop="wikiIds">
          <el-button type="primary" icon="Plus" plain @click="handleSelectWiki">关联知识库</el-button>
          <div>
            <el-tag v-for="(item, index) in wikiList" :key="index" class="tag_class">{{ item.name }}</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择知识库对话框 -->
    <SelectLibrary ref="SelectLibraryRefs" @confirm="SelectLibrary_confirm"></SelectLibrary>
    <!-- 选择人员权限对话框 -->
    <ManageMembers ref="ManageMembersRefs" :treeNodeId="appId" @onRefresh="ManageMembers_onRefresh">
    </ManageMembers>
  </div>
</template>

<script setup name="KnowledgeConfig" lang="ts">
import { aiqaApiWikiAppsList, aiqaApiWikiAppsCreate, aiqaApiWikiAppsUpdate, aiqaApiWikiAppsDelete, aiqaWikiAppsAppIdAssignPermissions } from '@/api/know/wikiApps/indexApi';

import SelectLibrary from '@/views/know/wikiApps/components/select-library.vue';
import ManageMembers from './components/manageMembers.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wiki_type } = toRefs<any>(proxy?.useDict('wiki_type'));

const dataList = ref<any>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const dialogFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: any = {
  id: undefined,
  appName: undefined,
  appKey: undefined,
  wikiType: undefined,
  wikiIds: undefined,
  wikiNames: undefined,
  description:undefined
}
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appName: undefined,
    params: {
    }
  },
  rules: {
    appName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    appKey: [
      { required: true, message: "秘钥不能为空", trigger: "blur" }
    ],
    wikiType: [
      { required: true, message: "类型不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "描述不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const SelectLibraryRefs: any = ref(null)
const wikiList = ref([])  //创建的时候选择的知识库列表
const wikiListNames = ref([])//编辑的时候回显的知识库列表

const ManageMembersRefs: any = ref(null)
const appId = ref(0)
/** 查询知识库配置11列表 */
const getList = async () => {
  loading.value = true;
  const res = await aiqaApiWikiAppsList(queryParams.value);
  dataList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  dialogFormRef.value?.resetFields();
  wikiList.value = []
  wikiListNames.value = []
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加知识库应用";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  const _id = row?.id || ids.value[0]
  // const res = await getKnowledgeConfig(_id);
  let wikiListNames = row.wikiNames ? row.wikiNames.split(",") : [];
  let wikiIds = row.wikiIds ? row.wikiIds.split(",") : [];
  wikiList.value = wikiIds.map(item => {
    return {
      id: item,
      name: wikiListNames[wikiIds.indexOf(item)]
    }
  })
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = "修改知识库应用";
}

/** 提交按钮 */
const submitForm = () => {
  // console.log(form.value);
  dialogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.wikiIds = wikiList.value.map(item => item.id).join(",")
      form.value.wikiNames = wikiList.value.map(item => item.name).join(",")
      if (form.value.id) {
        await aiqaApiWikiAppsUpdate(form.value).finally(() => buttonLoading.value = false);
      } else {
        await aiqaApiWikiAppsCreate(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _ids = row?.id ? [row.id] : ids.value;
  await proxy?.$modal.confirm('是否确认删除知识库配置11编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await aiqaApiWikiAppsDelete(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('aiqa/knowledgeConfig/export', {
    ...queryParams.value
  }, `knowledgeConfig_${new Date().getTime()}.xlsx`)
}

//选择知识库--打开知识库列表
const handleSelectWiki = () => {
  SelectLibraryRefs.value.visibleDialog = true
  SelectLibraryRefs.value.tableData = JSON.parse(JSON.stringify(wikiList.value))
}
// 选择知识库的Emit事件
const SelectLibrary_confirm = (val: any) => {
  wikiList.value = val
}
//字典转换翻译
const getDictDataLabel = (value: any) => {
  return proxy?.selectDictLabel(wiki_type.value, value);
}
//打开权限配置
const openRoleDialog = (row: any) => {
  appId.value = row.id
  nextTick(() => {
    ManageMembersRefs.value.addClick()
  })
}
// 人员权限对话框确定事件
const ManageMembers_onRefresh = (val) => {
  console.log(val);
  let userIds = []
  let userNames = []
  let deptIds = []
  let deptNames = []
  val.forEach(item => {
    if (item.type == 'user') {
      userIds.push(item.typeId)
      userNames.push(item.name)
    } else if (item.type == 'dept') {
      deptIds.push(item.typeId)
      deptNames.push(item.name)
    }
  })
  aiqaWikiAppsAppIdAssignPermissions(appId.value, {
    userIds: userIds,
    deptIds: deptIds,
    userNames: userNames,
    deptNames: deptNames
  }).then((res: any) => {
    proxy?.$modal.msgSuccess("操作成功");
  }).catch((err: any) => {
    console.log(err);
    proxy?.$modal.msgError("操作失败");
  })
}
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.tag_class {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>
